/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.util;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;

/**
 * @description: CharsetUtils
 * @author: zzh
 * @date: 2021/10/28 10:32
 */
public class CharsetUtils {

  /** ISO-8859-1 */
  public static final String ISO_8859_1 = "ISO-8859-1";
  /** UTF-8 */
  public static final String UTF_8 = "UTF-8";
  /** GBK */
  public static final String GBK = "GBK";

  /** ISO-8859-1 */
  public static final Charset CHARSET_ISO_8859_1 = StandardCharsets.ISO_8859_1;
  /** UTF-8 */
  public static final Charset CHARSET_UTF_8 = StandardCharsets.UTF_8;
  /** GBK */
  public static final Charset CHARSET_GBK;

  static {
    // 避免不支持GBK的系统中运行报错 issue#731
    Charset _CHARSET_GBK = null;
    try {
      _CHARSET_GBK = Charset.forName(GBK);
    } catch (UnsupportedCharsetException e) {
      // ignore
    }
    CHARSET_GBK = _CHARSET_GBK;
  }

  /**
   * 转换为Charset对象
   *
   * @param charsetName 字符集，为空则返回默认字符集
   * @return Charset
   * @throws UnsupportedCharsetException 编码不支持
   */
  public static Charset charset(String charsetName) throws UnsupportedCharsetException {
    return StrUtils.isBlank(charsetName) ? Charset.defaultCharset() : Charset.forName(charsetName);
  }

  /**
   * 系统默认字符集编码
   *
   * @return 系统字符集编码
   */
  public static String defaultCharsetName() {
    return defaultCharset().name();
  }

  /**
   * 系统默认字符集编码
   *
   * @return 系统字符集编码
   */
  public static Charset defaultCharset() {
    return Charset.defaultCharset();
  }
}
